//
//  WRSNfcHelp.swift
//  WRSNfcLib
//
//  Created by Admin on 2024/5/21.
//

import Foundation
import CoreNFC

@available(iOS 13.0, *)
public func NFCTagToNFCNDEFTag(model: NFCTag) -> NFCNDEFTag? {
    switch model {
    case let .feliCa(value):
        if let tag = value.asNFCFeliCaTag() {
           return tag
        }
        break
    case let .iso15693(value):
        if let tag = value.asNFCISO15693Tag() {
            return tag
        }
        break
    case let .iso7816(value):
        if let tag = value.asNFCISO7816Tag() {
            return tag
        }
        break
    case let .miFare(value):
        if let tag = value.asNFCMiFareTag() {
            return tag
        }
        break
    default:
        break
    }
    return nil
}

@available(iOS 13.0, *)
public func NFCTagToDic(model: NFCTag)-> [String: Any] {
    var result = [String: Any]()
    result["isAvailable"] = model.isAvailable

    switch model {
    case let .feliCa(value):
        result["type"] = "feliCa"
        if let tag = value.asNFCFeliCaTag() {
            result["value"] = [
                "currentIDm": NFCDataToHexStr(data: tag.currentIDm),
                "currentSystemCode": NFCDataToHexStr(data: tag.currentSystemCode)
            ]
           
        }
        break
    case let .iso15693(value):
        result["type"] = "iso15693"
        if let tag = value.asNFCISO15693Tag() {
            result["value"] = [
                "identifier": NFCDataToHexStr(data: tag.identifier),
                "icSerialNumber": NFCDataToHexStr(data: tag.icSerialNumber),
                "icManufacturerCode": tag.icManufacturerCode
            ]
        }
        break
    case let .iso7816(value):
        result["type"] = "iso7816"
        if let tag = value.asNFCISO7816Tag() {
            var value = [String: Any]()
            value["initialSelectedAID"] = tag.initialSelectedAID
            value["identifier"] = NFCDataToHexStr(data: tag.identifier)
            if let data = tag.historicalBytes {
                value["historicalBytes"] = NFCDataToHexStr(data: data)
            }
            if let data = tag.applicationData {
                value["applicationData"] = NFCDataToHexStr(data: data)
            }
            value["proprietaryApplicationDataCoding"] = tag.proprietaryApplicationDataCoding
            result["value"] = value
        }
        break
    case let .miFare(value):
        result["type"] = "miFare"
        if let tag = value.asNFCMiFareTag() {
            var value = [String: Any]()
            value["identifier"] = NFCDataToHexStr(data: tag.identifier)
            if let data = tag.historicalBytes {
                value["historicalBytes"] = NFCDataToHexStr(data: data)
            }
            result["value"] = value
        }
        break
    default:
        break
    }
    return result
}

func NFCDataToHexStr(data: Data)-> String {
    return data.map { String(format: "%02x", $0) }
        .joined()
}
